package com.ruihu.admin.common.validator.daterange;

import com.ruihu.admin.util.RhObjectUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

public class DateRangeValidator implements ConstraintValidator<DateRangeValidate, Object> {

    private String startDateTimeGetterName;

    private String endDateTimeGetterName;


    @Override
    public void initialize(DateRangeValidate dateRangeValidate) {
        this.startDateTimeGetterName = dateRangeValidate.startDateTimeGetter();
        this.endDateTimeGetterName = dateRangeValidate.endDateTimeGetter();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        try {
            Method startDateTimeMethod = o.getClass().getMethod(startDateTimeGetterName, null);
            Date startDate = (Date)startDateTimeMethod.invoke(o, null);
            Method endDateTimeMethod = o.getClass().getMethod(endDateTimeGetterName, null);
            Date endDate = (Date)endDateTimeMethod.invoke(o, null);
            if (RhObjectUtil.anyNull(startDate, endDate)) {
                return true;
            }
            return endDate.after(startDate)||endDate.equals(startDate);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}
